#!/bin/bash

# HDC端口扫描器 - 快速启动脚本

# 获取脚本所在目录的绝对路径
# 使用兼容的方法确保获取真实的绝对路径，避免符号链接问题
get_script_dir() {
    local source="${BASH_SOURCE[0]}"
    # 解析符号链接
    while [[ -L "$source" ]]; do
        local dir="$(cd -P "$(dirname "$source")" && pwd)"
        source="$(readlink "$source")"
        [[ $source != /* ]] && source="$dir/$source"
    done
    cd -P "$(dirname "$source")" && pwd
}

SCRIPT_DIR="$(get_script_dir)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

print_msg() {
    echo -e "${1}${2}${NC}"
}

show_banner() {
    clear
    print_msg $BLUE "════════════════════════════════════════════════════════════"
    print_msg $BLUE "                 HDC 无线调试端口扫描器"
    print_msg $BLUE "        自动扫描并连接 HarmonyOS 设备的无线调试端口"
    print_msg $BLUE ""
    print_msg $BLUE "                     作者: ZestBox"
    print_msg $BLUE "                    使用平台：mac"
    print_msg $BLUE "════════════════════════════════════════════════════════════"
    echo ""
}

check_dependencies() {
    local missing_deps=()
    
    if ! command -v hdc >/dev/null 2>&1; then
        missing_deps+=("hdc")
    fi
    
    # 检查完整版依赖
    if ! command -v nc >/dev/null 2>&1; then
        missing_deps+=("netcat")
    fi
    
    if ! command -v timeout >/dev/null 2>&1; then
        missing_deps+=("timeout")
    fi
    
    echo "${#missing_deps[@]}"
}

show_menu() {
    print_msg $YELLOW "请选择操作："
    echo ""
    print_msg $GREEN "  1) 启动端口扫描器   (开始扫描HDC端口)"
    print_msg $BLUE "  2) 环境设置        (检查和安装依赖)"
    print_msg $BLUE "  3) 查看帮助        (使用说明)"
    print_msg $RED "  4) 退出程序"
    echo ""
}

run_full_scanner() {
    local scanner_script="$SCRIPT_DIR/port_scanner.sh"
    
    if [[ ! -f "$scanner_script" ]]; then
        print_msg $RED "完整版扫描器文件不存在: $scanner_script"
        return 1
    fi
    
    print_msg $GREEN "启动端口扫描器..."
    echo ""
    "$scanner_script"
}
run_setup() {
    local setup_script="$SCRIPT_DIR/setup.sh"
    
    if [[ ! -f "$setup_script" ]]; then
        print_msg $RED "环境设置脚本不存在: $setup_script"
        return 1
    fi
    
    print_msg $GREEN "启动环境设置..."
    echo ""
    "$setup_script"
}

show_help() {
    print_msg $YELLOW "=== 使用说明 ==="
    echo ""
    print_msg $BLUE "1. 端口扫描器特点："
    print_msg $WHITE "   • 支持多线程并发扫描"
    print_msg $WHITE "   • 实时进度显示"
    print_msg $WHITE "   • 高级错误处理"
    print_msg $WHITE "   • 自动IP记忆功能"
    print_msg $WHITE "   • 支持中途停止扫描"
    echo ""
    print_msg $BLUE "2. 使用步骤："
    print_msg $WHITE "   • 运行扫描器，输入目标设备IP"
    print_msg $WHITE "   • 系统自动扫描所有端口"
    print_msg $WHITE "   • 找到可用端口后自动HDC连接"
    print_msg $WHITE "   • 按回车键可随时停止扫描"
    echo ""
    print_msg $BLUE "3. 依赖要求："
    print_msg $WHITE "   • hdc命令（HarmonyOS开发工具包）"
    print_msg $WHITE "   • netcat、coreutils等系统工具"
    print_msg $WHITE "   • 如有依赖缺失，可运行环境设置"
    echo ""
    print_msg $BLUE "4. HDC 安装："
    print_msg $WHITE "   • 从 HarmonyOS 开发者网站下载开发工具包"
    print_msg $WHITE "   • 将 hdc 命令添加到系统 PATH 中"
    print_msg $WHITE "   • 验证安装：hdc version"
    echo ""
}

main() {
    show_banner
    
    # 检查基本环境
    local missing_count
    missing_count=$(check_dependencies)
    
    if [[ $missing_count -gt 0 ]]; then
        print_msg $YELLOW "检测到 $missing_count 个依赖缺失"
        print_msg $YELLOW "   建议先运行环境设置 (选项 3)"
        echo ""
    fi
    
    while true; do
        show_menu
        
        echo -n "请输入选项 (1-4) [回车选择1]: "
        read -r choice
        
        # 如果直接回车，默认选择1
        if [[ -z "$choice" ]]; then
            choice=1
        fi
        
        echo ""
        
        case $choice in
            1)
                run_full_scanner
                local scanner_exit_code=$?
                if [[ $scanner_exit_code -eq 0 ]]; then
                    echo ""
                    echo -n "扫描器已结束，是否继续使用菜单？ (y/N): "
                    read -r continue_choice
                    if [[ "$continue_choice" != "y" && "$continue_choice" != "Y" ]]; then
                        print_msg $GREEN "感谢使用！"
                        exit 0
                    fi
                else
                    echo ""
                    echo -n "扫描器遇到问题，按回车返回菜单..."
                    read -r
                fi
                ;;
            2)
                run_setup
                ;;
            3)
                show_help
                ;;
            4)
                print_msg $GREEN "感谢使用！"
                exit 0
                ;;
            *)
                print_msg $RED "无效选项，请输入 1-4"
                ;;
        esac
        
        # 只有选择2、3或无效选项时才显示这个提示
        if [[ $choice -eq 2 || $choice -eq 3 ]] 2>/dev/null || ! [[ "$choice" =~ ^[1-4]$ ]]; then
            echo ""
            echo -n "按回车键继续..."
            read -r
        fi
        
        show_banner
    done
}

# 检查脚本是否在正确目录中运行
if [[ ! -f "$SCRIPT_DIR/port_scanner.sh" ]]; then
    print_msg $RED "错误：在当前目录中未找到扫描器脚本"
    print_msg $YELLOW "请确保在包含扫描器脚本的目录中运行此程序"
    print_msg $YELLOW "脚本目录: $SCRIPT_DIR"
    exit 1
fi

main "$@"